<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Group Service class for communication between controllers and persistent storage
 *
 * @category    RedCross
 * @package     RedCross_Service
 */
class Core_Service_Group extends RedCross_Service_ServiceAbstract
{
    /**
     * Constructor
     * @param Core_Gateway_Group $gateway
     */
    public function __construct(Core_Gateway_Group $gateway)
    {
        parent::__construct($gateway, 'Core_Model_Group');
    }

    public function create($data)
    {
        $this->checkAcl('create');

        $model = new Core_Model_Group();
        $model->fromArray($data);

        try {
            $result = $this->getGateway()->save($model);
        } catch(RedCross_Gateway_ValidationException $e) {
            $result = false;
        }
        return $result;
    }

    public function edit(Core_Model_Group $group, array $data)
    {
        $this->checkAcl('edit');

        $group->fromArray($data);
        $result = $this->getGateway()->save($group);
        if ($result) {
        	return true;
        }
        return false;
    }

    public function fetchAll()
    {
        $this->checkAcl('fetchAll');
        return parent::fetchAll();
    }

    public function fetchUsersNotInGroup($groupId)
    {
        $this->checkAcl('edit');
        $userGateway = $this->getGateway('Core_Gateway_User');
        return $userGateway->fetchUsersNotInGroup($groupId);
    }

    public function addUser($groupId, $userId)
    {
        $this->checkAcl('edit');
        return $this->getGateway()->addUser($groupId, $userId);
    }

    public function removeUser($groupId, $userId)
    {
        $this->checkAcl('edit');
        return $this->getGateway()->removeUser($groupId, $userId);
    }

    public function fetchById($id)
    {
        $this->checkAcl('fetch');
        return $this->getGateway()->fetchById($id);
    }

    public function fetchGroupNameById($id)
    {
        $this->checkAcl('fetch');
        return $this->getGateway()->fetchGroupNameById($id);
    }

}
